package com.lll.securitydemo.service;

import com.lll.securitydemo.dao.RoleDao;
import com.lll.securitydemo.dao.UserDao;
import com.lll.securitydemo.dto.entity.RoleEntity;
import com.lll.securitydemo.dto.entity.UserEntity;
import com.lll.securitydemo.dto.entity.UserRoleEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

/**
 * Description: 自定义用户信息接口实现，查看用户所有的信息，包括权限<br/>
 * 实现UserDetailsService接口
 *
 * @author LLL<br                                                               />;
 * @taskId <br/>
 * <br/>
 */
@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    /**
     * @param s 重写根据用户名查找用户方法
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(s);
        UserEntity selectOne = userDao.selectOne(userEntity);
        if (!Objects.isNull(selectOne)) {
            Example example = new Example(UserRoleEntity.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", selectOne.getId());
            List<RoleEntity> authorities = roleDao.selectByExample(criteria);
            selectOne.setAuthorities(authorities);
        }
        return selectOne;
    }
}
